<template>
    <div>
       <Breadcrumb :breadcrumba="breadcrumba" :breadcrumbb="breadcrumbb"></Breadcrumb>
       <el-card class="box-card">
          
            <el-row :gutter="50">
                <el-col :span="8">
                     <el-input placeholder="请输入内容" v-model="userListinfo.query" class="input-with-select" clearable
                     @clear="getUserList()">
                        <el-button slot="append" icon="el-icon-search" @click="getUserList()"></el-button>
                    </el-input>
                </el-col>
                <el-col :span="12">
                    <el-button type="primary" @click="dialogVisible = true">添加用户</el-button>
                </el-col>
            </el-row>
            <!-- 表格区域 -->
        <!-- <Table :usersList="tableInfo"></Table> -->
         <template>
            <el-table
            :data="userList"
            border
            stripe
            size="mini"
            style="width: 100%">
            <el-table-column
                align="center"
                type="index"
                label="序号"
                width="80">
            </el-table-column>
            <el-table-column
                prop="username"
                label="姓名"
                width="180">
            </el-table-column>
            <el-table-column
                prop="email"
                label="邮箱"
                width="180">
            </el-table-column>
            <el-table-column
                prop="mobile"
                label="电话">
            </el-table-column>

            <el-table-column
                prop="role_name"
                label="角色">
            </el-table-column>
            <el-table-column
               
                label="状态">
                <template slot-scope="scope">
                    <!-- 作用于插槽  绑定row里的属性-->
                    <el-switch
                    v-model="scope.row.mg_state"
                    @change="userStateChanged(scope.row)">
                    </el-switch>
                </template>
            </el-table-column>
            <el-table-column
                label="操作">
                 <template slot-scope="scope"> 
                    <el-tooltip class="item" effect="dark" content="修改" placement="top" :enterable="false">
                        <el-button type="primary" icon="el-icon-edit" @click="xiugai(scope.row.id)"></el-button>
                    </el-tooltip>
                    <el-tooltip class="item" effect="dark" content="删除" placement="top" :enterable="false">
                            <el-button type="danger" icon="el-icon-delete" @click="delUser(scope.row.id)"></el-button>    
                    </el-tooltip>
                    <el-tooltip class="item" effect="dark" content="分配角色" placement="top" :enterable="false">
                        <el-button type="warning" icon="el-icon-s-tools" @click="userRole(scope.row)"></el-button>
                    </el-tooltip>
                    
                 </template>
            </el-table-column>
            </el-table>
        </template>
        <!-- 分页 -->
        <div class="block">
            <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="userListinfo.pagenum"
            :page-sizes="[1, 2, 5, 10]"
            :page-size="userListinfo.pagesize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
            </el-pagination>
        </div>
        </el-card>
        <!-- 添加用户对话框 -->
        <el-dialog
        title="添加用户"
        :visible.sync="dialogVisible"
        width="50%"
        :before-close="handleClose"
        @close="addDialogClosed">
        <!-- 内容主体区域 -->
            <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px" class="demo-ruleForm">
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="addForm.username"></el-input>
                </el-form-item>

                <el-form-item label="密码" prop="password">
                    <el-input v-model="addForm.password"></el-input>
                </el-form-item>

                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="addForm.email"></el-input>
                </el-form-item>

                <el-form-item label="手机号" prop="mobile">
                    <el-input v-model="addForm.mobile"></el-input>
                </el-form-item>
            </el-form>    
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="addUser">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 修改用户 -->
        <el-dialog
        title="修改用户信息"
        :visible.sync="editDialogVisible"
        width="50%"
        :before-close="handleClose"
        @close="editDialogClosed">
       
            <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="70px" >
                <el-form-item label="用户名" >
                    <el-input v-model="editForm.username" :disabled="true"></el-input>
                </el-form-item>

                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="editForm.email"></el-input>
                </el-form-item>

                <el-form-item label="手机号" prop="mobile">
                    <el-input v-model="editForm.mobile"></el-input>
                </el-form-item>
            </el-form>    
            <span slot="footer" class="dialog-footer">
                <el-button @click="editDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="changeUser">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 分配角色 -->
        <el-dialog
        title="分配角色"
        :visible.sync="userRoledialogVisible"
        width="50%"
        :before-close="handleClose"
        @close="roleDialogClosed">
            <p>当前用户：{{userInfo.username}}</p>
            <p>当前角色：{{userInfo.role_name}}</p>
            分配新角色：<el-select v-model="newRole" placeholder="请选择" >
                        <el-option
                        v-for="item in rolesList"
                        :key="item.id"
                        :label="item.roleName"
                        :value="item.id">
                        </el-option>
                    </el-select>     
            <span slot="footer" class="dialog-footer">
                <el-button @click="userRoledialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="setUserRole">确 定</el-button>
            </span>
        </el-dialog>
    </div>
    
    
</template>

<script>
import Breadcrumb from "../../components/Breadcrumb"
import {getUserList,chuangeUserState,addUser,findUser,changeUser,deleteUser,setUserRole} from "../../api/user"
import {getRolesList} from "../../api/roles"
// import Table from "../../components/Table"
    export default {
        components:{
            Breadcrumb,
            // Table
        },
        data(){
            // 自定义校验规则
            // 校验电话号
             var checkMobile = (rule, value, callback) => {
                const regMobile = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
                if (value === '') {
                callback(new Error('请输入电话'));
                } else {
                    
                        if(regMobile.test(value)){
                            return callback()
                        }
                    
                    callback(new Error('请输入正确的电话号'))
                }
            };
            
            return{
                breadcrumba:'',
                breadcrumbb:'',
                // search:'',
                userListinfo:{
                    query: '',
                    pagenum: 1,
                    pagesize: 2
                },
                userList:[],
                pagenum:null,
                total:null,
                // value1:true
                dialogVisible:false,
                addForm:{
                    username:'',
                    password:'',
                    email:'',
                    mobile:''
                },
                addFormRules:{
                    username:[
                        // required 必填项
                        { required:true,message:"请输入用户名",trigger:'blur'},
                        { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
                    ],
                    password:[
                        { required:true,message:"请输入用户名",trigger:'blur'},
                        { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
                    ],
                    email:[
                        { required: true, message: '请输入邮箱地址', trigger: 'blur' },
                        { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
                    ],
                    mobile:[
                        { validator: checkMobile, trigger: ['blur', 'change'] },
                        { required: true, message: '请输入电话号', trigger: 'blur' },
                        // { pattern: /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,message: '请输入正确的电话', trigger: ['blur', 'change']},
                    ]
                },
                editDialogVisible:false,
                editForm:{},
                editFormRules:{
                    email:[
                        { required: true, message: '请输入邮箱地址', trigger: 'blur' },
                        { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
                    ],
                     mobile:[
                        { validator: checkMobile, trigger: ['blur', 'change'] },
                        { required: true, message: '请输入电话号', trigger: 'blur' },
                    ]
                },
                userRoledialogVisible:false,
                userInfo:{},
                rolesList:[],
                newRole:''
            }
        },
        created(){
            this.breadcrumba=sessionStorage.getItem('breadcrumba')
            this.breadcrumbb=sessionStorage.getItem('breadcrumbb')
            this.getUserList()
        },
        methods:{
            search(){
                console.log("llll");
            },
            async getUserList(){
                let res = await getUserList(this.userListinfo)
                console.log(res.data,"用户列表");
                this.userList = res.data.data.users 
                this.pagenum = res.data.data.pagenum
                this.total = res.data.data.total
                this.value1 = res.data.data.mg_state
            },
            handleSizeChange(newSize) {
                // console.log(newSize,"11");
                this.userListinfo.pagesize = newSize
                this.getUserList()
            },
            // 监听页码值改变
            handleCurrentChange(newPage){
                // console.log(newPage,"22");
                this.userListinfo.pagenum = newPage
                this.getUserList()
            },
            // 监听状态改变 改变角色状态
            async userStateChanged(userListinfo){
                // console.log(userListinfo,"fff");
                let res = await chuangeUserState(userListinfo)
                // console.log(res,"哈哈哈");
                // console.log(res.data.meta.status,"lll");
                if(res.data.meta.status == 200){
                    this.$message({
                        message: res.data.meta.msg,
                        type: 'success'
                        });
                }else{
                     this.$message.error('设置失败')
                     userListinfo.mg_state = !userListinfo.mg_state
                }
            },
             handleClose(done) {
                this.$confirm('确认关闭？')
                .then(_ => {
                    done();
                })
                .catch(_ => {});
            },
            async xiugai(id){
                // console.log(id,"fffr");
                let {data:res} = await findUser(id)
                console.log(res,"id找用户");
                if(res.meta.status !== 200){
                   return this.$message.error('查找用户失败')
                }

                this.editForm = res.data
                // console.log(this.editForm);
                this.editDialogVisible = true
                
            },
            // 点击添加  先进行表单预校验
            addUser(){
                console.log(this,"this");
                // 表单预校验
                this.$refs.addFormRef.validate(async valid=>{
                    console.log(valid,"预校验");
                    if(!valid){
                        this.$message.error('请填写正确的格式')
                        return
                    };
                    // 正确可以发起添加请求
                    let res = await addUser(this.addForm)
                    console.log(res,"jjjjjjskskskjs");
                    if(res.data.meta.status == 201 || res.data.meta.status == 200){
                        this.$message({
                            message: res.data.meta.msg,
                            type: 'success'
                            });
                        this.getUserList()
                    }else{
                        this.$message.error('添加失败')
                    }
                    this.dialogVisible = false
                    })
                // console.log(this.addForm,"vvvv"); 
            },
            // 添加用户关闭 重置formn表单 用 refs绑定的重置
            addDialogClosed(){
                this.$refs.addFormRef.resetFields()
            },
            // 修改用户的操作
            changeUser(){
                this.$refs.editFormRef.validate(async valid=>{
                     if(!valid){
                        this.$message.error('请填写正确的格式')
                        return
                    };
                    let {data:res} = await changeUser({id:this.editForm.id,query:{email:this.editForm.email,mobile:this.editForm.mobile}})
                    if(res.meta.status == 200){
                        this.$message({
                            message: res.meta.msg,
                            type: 'success'
                            });
                        this.getUserList()
                    }else{
                        this.$message.error('添加失败')
                    }
                })
                this.editDialogVisible = false
            },
            editDialogClosed(){
                    this.$refs.editFormRef.resetFields()
            },
            delUser(id){
                // console.log(id,"删除用户的id");
                this.$confirm('是否删除当前用户？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
                }).then(async () => {
                    console.log(id,"的辅导辅导辅导辅导");
                    let {data:res} = await deleteUser(id)
                    this.getUserList()
                    // console.log(res,"删除之后的结果");
                this.$message({
                    type: 'success',
                    message: '删除成功!'
                });
                }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });          
                });
            },
            async userRole(userInfo){

                // 获取角色裂变
                let {data:res} = await getRolesList()
                console.log(res,"用户页面获取的角色列表");
                if(res.meta.status !== 200){
                    return this.$message.error("获取角色列表失败")
                }
                this.rolesList = res.data
                this.userInfo = userInfo 
                this.userRoledialogVisible = true 
            },
            async setUserRole(){
                // 不能是 空的
                if(!this.newRole){
                    return this.$message.error("请选择要分配的角色！")
                }
                console.log(this.newRole,this.userInfo.id ,"新的角色id");
                let {data:res} = await setUserRole({id:this.userInfo.id,rid:{rid:this.newRole}})
                console.log(res,"更改角色之后返回的值");

                if(res.meta.status !== 200){
                    return this.$message.error("添加角色失败！")
                }

                this.$message.success("添加角色成功！")
                this.getUserList()
                this.userRoledialogVisible = false 

            },
            // 弹出框关闭的时候 重置表单 重新设置为空的就行了
            roleDialogClosed(){
                this.userInfo = {}
                this.newRole = ''
            }
        }
    }
</script>

<style scoped>
    .el-table{
        margin-top: 15px;
        font-size: 14px;
    }
    .el-pagination{
        margin-top: 20px;
        background: #fff;
        /* padding: 5px; */
    }
</style>